package com.asset.dispoal.file.agreementCaseData.service.commom;

import com.asset.dispoal.file.agreementCaseData.domain.db.entity.FileAgreement;
import com.asset.dispoal.file.agreementCaseData.domain.db.mapper.FileAgreementMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.File;

/**
 * @author qr
 * @date 2022/4/6$
 */
@Component
public class ImportExcelCommand implements BaseCommand<MultipartFile, Result> {

    @Autowired
    private Environment environment;

    @Autowired
    FileAgreementMapper fileAgreementMapper;

    @Autowired
    private BaseIdeable<String> idWorker;

    @Override
    public Result<String> execute(MultipartFile multipartFile) {
        String filePath = null;
        String headUrl = environment.getProperty("file.evidence.url");
        String property = environment.getProperty("file.import.url");
        String generateId = idWorker.generateId();
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try {
            filePath = property + "/" + generateId + "." + suffix;
            multipartFile.transferTo(new File(headUrl + "/" + filePath));
            FileAgreement fileAgreement = new FileAgreement();
            fileAgreement.setId(generateId + "." + suffix);
            fileAgreement.setFileName(generateId);
            fileAgreement.setFilePath(filePath);
            fileAgreement.setFileOriginalName(originalFilename);
            fileAgreementMapper.insert(fileAgreement);
        } catch (Exception e) {
            throw new BusinessException(e);
        }
        return Result.ok(filePath);

    }
}
